<?php

namespace ShowStop\TelevisionBundle\Controller;

use ShowStop\TelevisionBundle\Entity\EditSeries;

use Symfony\Component\Validator\Constraints\Date;
use ShowStop\TelevisionBundle\Entity\Ratings;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;


class DefaultController extends Controller
{
     
    public function seriesAction($id) 
    {
    	$em = $this->getDoctrine()->getEntityManager();
    	
    	$query = $em->createQuery( 'SELECT s FROM ShowStopTelevisionBundle:Series s WHERE s.id = ' . $id );
    	
    	$series = $query->getResult();
    	
    	$user = $this->get('security.context')->getToken()->getUser();
    	
    	if($user !== 'anon.')
    	{
    		$values['hdnRating'] = 0;
    		$values['hdnUserID'] = $this->get('security.context')->getToken()->getUser()->getId();
    		$values['hdnSeriesID'] = $id;
    	
    		//create rating form
    		$form = $this->createFormBuilder($values)
    		->add('hdnRating', 'hidden')
    		->add('hdnUserID', 'hidden')
    		->add('hdnSeriesID', 'hidden')
    		->getForm();
    	}
    	
    	$conn = $this->get('database_connection');
		$suggest = $conn->fetchAll( "SELECT s.id, s.name as name FROM series s INNER JOIN user_favorite u ON s.id = u.series_id WHERE u.user_id IN ( SELECT u.user_id FROM user_favorite u WHERE u.series_id = ".$id." )and s.id <> ".$id." LIMIT 5");
    
    	$OverallRatingclass = "nostar";
    	$query = $em->createQuery("select avg(r.rating) as rating from ShowStopTelevisionBundle:Ratings r where r.seriesid = ". $id);
    	$result = $query->getOneOrNullResult();
    	$avg = 0;
    	if($result["rating"] != null)
    	{
    		$avg = round($result["rating"],1) ;
    		if($result["rating"] > 0.5 and $result["rating"] < 1.5)
    		{
    			$OverallRatingclass = "onestar";
    		}
    		else if ($result["rating"] >= 1.5 and $result["rating"] < 2.5 )
    		{
    			$OverallRatingclass = "twostar";
    		}
    		else if ($result["rating"] >= 2.5 and $result["rating"] < 3.5 )
    		{
    			$OverallRatingclass = "threestar";
    		}
    		else if ($result["rating"] >= 3.5 and $result["rating"] < 4.5 )
    		{
    			$OverallRatingclass = "fourstar";
    		}
    		else if ($result["rating"] >= 4.5 )
    		{
    			$OverallRatingclass = "fivestar";
    		}  
    	}
    	
    	$result = null;
    	if($user !== 'anon.')
    	{
    		$UserRatingclass = "nostar";
    		$query = $em->createQuery('select r.rating from ShowStopTelevisionBundle:Ratings r where r.seriesid = '. $id .'and r.userid =' . $values['hdnUserID']);
    		$result = $query->getOneOrNullResult();
    		 
    		if($result != null)
    		{
    			if($result["rating"] > 0.5 and $result["rating"] < 1.5)
    			{
    				$UserRatingclass = "onestar";
    			}
    			else if ($result["rating"] >= 1.5 and $result["rating"] < 2.5 )
    			{
    				$UserRatingclass = "twostar";
    			}
    			else if ($result["rating"] >= 2.5 and $result["rating"] < 3.5 )
    			{
    				$UserRatingclass = "threestar";
    			}
    			else if ($result["rating"] >= 3.5 and $result["rating"] < 4.5 )
    			{
    				$UserRatingclass = "fourstar";
    			}
    			else if ($result["rating"] >= 4.5 )
    			{
    				$UserRatingclass = "fivestar";
    			}
    		}    
    	
    		return $this->render('ShowStopTelevisionBundle:Default:series.html.twig', array('series' => $series, 'form' => $form->createView(), 'OverallRating' => $OverallRatingclass, 'UserRating' => $UserRatingclass, 'suggest' => $suggest, 'AvgRating' => $avg) );
    	}
    	else
    	{
    		return $this->render('ShowStopTelevisionBundle:Default:series.html.twig', array('series' => $series, 'OverallRating' => $OverallRatingclass, 'suggest' => $suggest, 'AvgRating' => $avg ) );
    	}
    }
    
    public function add_ratingAction(Request $request)
    {
    	 
    	$form = $this->createFormBuilder( array() )
    	->add('hdnRating', 'hidden')
    	->add('hdnUserID', 'hidden')
    	->add('hdnSeriesID', 'hidden')
    	->getForm();
    	 
    	if ($request->getMethod() == 'POST') {
    		 
    		$form->bindRequest($request);
    		$data = $form->getData();
    		 
    		$em = $this->getDoctrine()->getEntityManager();
    		 
    		$query = $em->createQuery( 'SELECT r FROM ShowStopTelevisionBundle:Ratings r WHERE r.seriesid = ' .$data['hdnSeriesID'] .'and r.userid =' .$data['hdnUserID']);
    		 
    		$usrRating = $query->getResult();
    
    		//add new rating
    		if(empty($usrRating))
    		{
    			$rating = new Ratings();
    			$rating->setSeriesId($data['hdnSeriesID']);
    			$rating->setUserId($data['hdnUserID']);
    			$rating->setRating($data['hdnRating']);
    			$em->persist($rating);
    			$em->flush();
    	   
    		}
    		else //update existing rating
    		{
    			$rating = $usrRating[0];
    			$rating->setRating($data['hdnRating']);
    			$em->persist($rating);
    			$em->flush();
    				
    		}
    
    	}
    	return $this->redirect( $this->generateUrl( "_seriespage", array( 'id' => $data["hdnSeriesID"] ) ) );
    }
    
    public function upcomingAction() {
    	$em = $this->getDoctrine()->getEntityManager();
    	
    	$query = $em->createQuery( 'SELECT s FROM ShowStopTelevisionBundle:Series s WHERE s.return_date >= \'' . date("Y-m-d") . '\' ORDER BY s.return_date' );
    	
    	$series = $query->getResult();
    	
    	return $this->render('ShowStopTelevisionBundle:Default:upcoming.html.twig', array('series' => $series, 'oldDate' => '' ) );
    }
    
    public function editSeriesAction(Request $request, $input = "0" )
    {
    	$em = $this->getDoctrine()->getEntityManager();
    	$query = $em->createQuery( 'SELECT s FROM ShowStopTelevisionBundle:Series s WHERE s.id = ' . $input );
    	$series = $query->getOneOrNullResult();
    	
    	//create the edit form values
    	$editSeries = new EditSeries();
    	$editSeries->setSeriesID( $series->getId() );
    	$editSeries->setName( $series->getName() );
    	$editSeries->setFirstAired( $series->getFirstAired() );
    	$editSeries->setNetwork( $series->getNetwork() );
    	$editSeries->setStatus( $series->getStatus() );
    	$editSeries->setDescription( $series->getDescription() );
    	$editSeries->setReturnDate( $series->getReturnDate() );
    	
    	//create the edit form
    	$form = $this->createFormBuilder( $editSeries )
    	->add('seriesID', 'hidden')
    	->add('name', 'hidden')
    	->add('first_aired', 'text',array( 'required' => false, 'attr' => array( 'class' => 'hasDatePicker' ) ) )
    	->add('network', 'text', array( 'required' => false ) )
    	->add('status', 'choice', 
    				   array('choices' => array('Starting' => 'Starting', 'Continuing' => 'Continuing', 'Ended' => 'Ended') ) )
    	->add('description', 'textarea', array( 'required' => false ) )
    	->add('return_date', 'text', array( 'required' => false, 'attr' => array( 'class' => 'hasDatePicker' ) ) )
    	->add('file', 'file', array( 'required' => false ) )
    	->add('source', 'textarea', array( 'required' => false ) )
    	->add('comment', 'textarea', array( 'required' => false ) )
    	->getForm();
    	
    	 
    	if ( $request->getMethod() == "POST" ) {
    		//get post vars
    		$form->bindRequest($request);
    		
    		//get the user who submitted the entry
    		$user = $this->get('security.context')->getToken()->getUser();
    		
    		$editSeries->setUserID( $user->getId() );
    		$editSeries->setSubmissionStatus( "pending" );
    		
    		
    		
    		//persist to db
    		$em->persist( $editSeries );
    		$em->flush();
    		
    		//return back to the page you edited
    		return $this->redirect( $this->generateUrl('_seriespage', array('id' => $editSeries->getSeriesId() )));
    	}
    	 
    	
    
    	
    	 
    	// array that saves all the ranges needed in the page
    	$status = array( "Ended" , "Continuing" , "No Data" );
    	 
    
    	return $this->render('ShowStopTelevisionBundle:Default:editSeries.html.twig', array('form' => $form->createView(), 'status' => $status));
    }
    
	
}
